package cn.sicnu.cs.employment.rest;


import cn.sicnu.cs.employment.common.ResultInfo;
import cn.sicnu.cs.employment.common.ResultInfoUtil;
import cn.sicnu.cs.employment.common.util.BeanConvertUtils;
import cn.sicnu.cs.employment.domain.entity.*;
import cn.sicnu.cs.employment.domain.vo.BackgroundInfoVo;
import cn.sicnu.cs.employment.domain.vo.BgAppealVo;
import cn.sicnu.cs.employment.domain.vo.CompanyInfoVo;
import cn.sicnu.cs.employment.domain.vo.EmployeeInfoVo;
import cn.sicnu.cs.employment.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static cn.sicnu.cs.employment.common.Constants.NOT_AVAILABLE;
import static cn.sicnu.cs.employment.common.util.RequestUtil.getCurrentUrl;
import static cn.sicnu.cs.employment.common.util.RequestUtil.getCurrentUser;

@Slf4j
@RestController
@RequestMapping("/com")
@RequiredArgsConstructor
public class CompanyResource {

    private final ICompanyService companyService;
    private final IBgAppealService appealService;
    private final IEmployeeService employeeService;
    private final IBackgroundCommentService commentService;
    private final IAdminRoleService adminService;

    @GetMapping("/info")
    public ResultInfo<CompanyInfoVo> getCompanyInfo() {
        User currentUser = getCurrentUser();
        val companyInfo = companyService.getCompanyInfo(currentUser.getId());
        val companyInfoVo = new CompanyInfoVo();
        BeanUtils.copyProperties(companyInfo, companyInfoVo);
        //补充邮箱和电话
        CompanyInfoVo companyInfoToSend = companyInfoVo
                .withUsername(currentUser.getUsername())
                .withMobile(currentUser.getMobile())
                .withEmail(currentUser.getEmail())
                .withLogo(companyService.getHeadImg(currentUser.getId()));
        return ResultInfoUtil.buildSuccess(getCurrentUrl(), companyInfoToSend);
    }

    @PostMapping("/emp")
    public ResultInfo<Void> addEmployee(@RequestBody Map<String, String> infos) {
        Long empId = null;
        try {
            empId = Long.valueOf(infos.get("empId"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        companyService.addEmployee(empId);
        return ResultInfoUtil.buildSuccess(getCurrentUrl());
    }

    @DeleteMapping("/emp/{empId}")
    public ResultInfo<Void> deleteEmployee(@PathVariable("empId") Long empId) {
        companyService.deprecateEmployee(empId);
        return ResultInfoUtil.buildSuccess(getCurrentUrl());
    }

    /**
     * @param status 0；招聘，》》 1；在职；》》 2；离职
     */
    @GetMapping("/emp")
    public ResultInfo<List<EmployeeInfoVo>> getAllEmployee(@RequestParam("status") Long status) {
        List<EmployeeInfo> employees = companyService.getEmployeesByStatus(status);
        List<EmployeeInfoVo> employeeVos = new LinkedList<>();
        for (EmployeeInfo employee : employees) {
            employeeVos.add(
                    BeanConvertUtils.toEmpVo(employee)
            );
        }
        // 为每位员工附上入职时间（离职时间）
        Long comId = companyService.getComIdById(getCurrentUser().getId());
        for (EmployeeInfoVo employeeVo : employeeVos) {
            EmployeeCompany empComInfo = companyService.getEmpComInfo(comId, employeeVo.getId());
            employeeVo.setEmpCom(empComInfo);
        }
        return ResultInfoUtil.buildSuccess(getCurrentUrl(), employeeVos);
    }

    /**
     * 添加评价
     */
    @PostMapping("/comment")
    public ResultInfo<Void> addBackGroundInfo(@RequestBody @Valid BackgroundComment infoVo) {
        BackgroundComment commentToSave = BackgroundComment.builder()
                .judgeId(getCurrentUser().getId())
                .empId(infoVo.getEmpId())
                .jobContent(infoVo.getJobContent())
                .jobResult(infoVo.getJobResult())
                .jobScore(infoVo.getJobScore())
                .comId(companyService.getComIdById(getCurrentUser().getId()))
                .build();
        commentService.insertCommment(commentToSave);
        return ResultInfoUtil.buildSuccess(getCurrentUrl());
    }

    /**
     * 删除评价
     */
    @DeleteMapping("/comment/{id}")
    public ResultInfo<Void> deleteBackgroundInfo(@PathVariable("id") Long id) {
        if (!commentService.isAvailable(id)) {
            return ResultInfoUtil.buildError(NOT_AVAILABLE, "不能对7天前新增的记录操作", getCurrentUrl());
        }
        commentService.deleteInfoById(id);
        return ResultInfoUtil.buildSuccess(getCurrentUrl());
    }

    /**
     * 公司获取所有各种情况的申诉/申请
     * 【type】1-申请，2-申诉
     * 【status】-1未处理，0驳回，1批准(不发送则获取所有)
     */
    @GetMapping("/appeal")
    public ResultInfo<List<BgAppealVo>> getAllAppeals(@RequestParam(value = "type", required = false) Integer type,
                                                      @RequestParam(value = "status", required = false) Integer status,
                                                      @RequestParam(value = "start", required = false) String start,
                                                      @RequestParam(value = "end", required = false) String end) {
        List<BgAppeal> appeals = appealService.getAllAppealsByCom(companyService.getComIdById(getCurrentUser().getId()),
                type, status, start, end);
        List<BgAppealVo> appealVos = new LinkedList<>();
        for (BgAppeal appeal : appeals) {
            appealVos.add(
                    BeanConvertUtils.toBgAppeal(appeal,
                            employeeService.getProjectExpById(appeal.getExpProId()),
                            employeeService.getUserInfoById(appeal.getEmpId()),
                            adminService.getInfo(appeal.getRespId())
                    )
            );
        }
        return ResultInfoUtil.buildSuccess(getCurrentUrl(), appealVos);
    }

    /**
     * 处理申诉/申请
     */
    @PostMapping("/appeal")
//    public ResultInfo<Void> handleAppeal(@RequestParam("appealId") Long appealId,
//                                         @RequestParam("status") Integer status,
//                                         @RequestParam("content") String content) {
    public ResultInfo<Void> handleAppeal(@RequestBody Map<String, String> infos) {
        String content = infos.get("content");
        Long appealId = null;
        try {
            appealId = Long.valueOf(infos.get("appealId"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Integer status = null;
        try {
            status = Integer.valueOf(infos.get("status"));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        BgAppeal respAppeal = BgAppeal.builder()
                .id(appealId)
                .respId(getCurrentUser().getId())
                .respContent(content)
                .respStatus(status)
                .respTime(dateFormat.format(new Date()))
                .build();
        appealService.saveAppeal(respAppeal, null);
        //TODO 处理申请成功时候的信息
        BgAppeal appeal = appealService.getAppealsById(appealId);
        if (appeal.getType() == 1 && status == 1) {
            appealService.approveAppeal(appeal.getExpProId());
        }
        return ResultInfoUtil.buildSuccess(getCurrentUrl());
    }

    @PostMapping("/bg")
    public ResultInfo<Void> addEmployeeBackgroundInfo(@RequestBody @Valid EmployeeExpProject info) {
        EmployeeExpProject bgToSave = EmployeeExpProject.builder()
                .empId(info.getEmpId())
                .comId(companyService.getComIdById(getCurrentUser().getId()))
                .content(info.getContent())
                .project(info.getProject())
                .time(info.getTime())
                .position(info.getPosition())
                .description(info.getDescription())
                .evaluate(info.getEvaluate())
                .build();
        employeeService.saveProjectExp(bgToSave);
        return ResultInfoUtil.buildSuccess(getCurrentUrl());
    }

    @DeleteMapping("/bg/{id}")
    public ResultInfo<Void> deleteEmployeeBackgroundInfo(@PathVariable("id") Long id) {
        if (!employeeService.isBgAvailable(id)) {
            return ResultInfoUtil.buildError(NOT_AVAILABLE, "不能对30天前新增的记录操作", getCurrentUrl());
        }
        employeeService.deleteProjectExp(id);
        return ResultInfoUtil.buildSuccess(getCurrentUrl());
    }
}